package com.tnovoselec.android.feed.handler.async;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.concurrent.Callable;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import android.content.Context;
import android.util.Log;

import com.nth.android.Util;
import com.tnovoselec.android.favorites.entity.MeteoFavoritesDto;
import com.tnovoselec.android.feed.handler.WeatherCityParser;
import com.tnovoselec.android.feed.handler.WeatherDataParser;
import com.tnovoselec.android.feed.handler.resultholders.WeatherResultHolder;


public class DownloadWeather implements Callable<Boolean> {

	public static long CACHE_VALIDITY = 15 * 60 * 1000;

	private final String TAG = DownloadWeather.class.getSimpleName();

	private String xmlUrl;
	private Context context;
	private boolean fromCache;

	public DownloadWeather(String xmlUrl, Context context, boolean fromCache) {
		super();
		this.xmlUrl = xmlUrl;
		this.context = context;
		this.fromCache = fromCache;
	}

	@Override
	public synchronized Boolean call() throws Exception {
		HttpURLConnection connection = null;
		InputStream is = null;

		try {
			if (Util.fileExistsHex(xmlUrl, context) && Util.getFileHex(xmlUrl, context).lastModified() < CACHE_VALIDITY) {
				// is = Util.readFile(xmlUrl, context);
			} else if (!fromCache) {
				// TODO ubaciti u Util framework
				URL imageUrl = new URL(xmlUrl);
				connection = (HttpURLConnection) imageUrl.openConnection();
				connection.setConnectTimeout(Util.HTTP_CONNECT_TIMEOUT);
				connection.setReadTimeout(Util.HTTP_READ_TIMEOUT);
				connection.setDoInput(true);
				connection.connect();

				is = connection.getInputStream();
				Util.fileCreate(xmlUrl, is, context);
			}
			if (Util.fileExistsHex(xmlUrl, context)) {
				is = Util.readFile(xmlUrl, context);
			} else {
				return Boolean.FALSE;
			}
			WeatherCityParser parser = new WeatherCityParser();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser sp = factory.newSAXParser();
			sp.parse(is, parser);

			final List<MeteoFavoritesDto> items = parser.getWeather();
			for (MeteoFavoritesDto weatherDto : items) {
				final WeatherDataParser dataParser = new WeatherDataParser(weatherDto);
				sp.parse(new URL(weatherDto.getUrl()).openStream(), dataParser);
			}
			WeatherResultHolder.init(items);
		} catch (Exception ex) {
			Log.e(TAG, ex.getMessage(), ex);
			return Boolean.FALSE;
		}
		return Boolean.TRUE;
	}

}
